package com.groupbuying.settleproducer.service.impl;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.exception.ONSClientException;
import com.groupbuying.settleproducer.connector.*;
import com.groupbuying.settleproducer.constants.*;
import com.groupbuying.settleproducer.context.FilterContextHandler;
import com.groupbuying.settleproducer.domain.*;
import com.groupbuying.settleproducer.mq.SettleMQConfig;
import com.groupbuying.settleproducer.service.*;
import com.groupbuying.settleproducer.utils.DateUtils;
import com.groupbuying.settleproducer.utils.JsonUtils;
import com.groupbuying.settleproducer.utils.MD5Utils;
import com.groupbuying.settleproducer.utils.RefundParamsCheckUtils;
import com.groupbuying.settleproducer.utils.apiresult.ApiResult;
import com.groupbuying.settleproducer.utils.apiresult.ApiResultCode;
import com.groupbuying.settleproducer.utils.redis.RedisUtils;
import feign.Feign;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.el.lang.ELArithmetic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SettleRefundServiceImpl implements SettleRefundService {

    private static final Logger logger = LoggerFactory.getLogger(SettleRefundServiceImpl.class);

    @Autowired
    private YSFeign ysFeign;

    @Autowired
    private OrderFeign orderFeign;

    @Autowired
    private StoreFeign storeFeign;

    @Autowired
    private PayFeign payFeign;

    @Autowired
    private CurrencyFeign currencyFeign;

    @Autowired
    private SysconfigFeign sysconfigFeign;

    @Autowired
    private CheetahFeign cheetahFeign;

    @Autowired
    private FinancialFeign financialFeign;

    @Autowired
    private CustomerFeign customerFeign;

    @Autowired
    private SettleUshopRefundService settleUshopRefundService;

    @Autowired
    private SettleUshopSplitRluesService settleUshopSplitRluesService;

    @Autowired
    private SettleUshopFlowStoreService settleUshopFlowStoreService;

    @Autowired
    private SettleUshopFlowPlantformService settleUshopFlowPlantformService;

    @Autowired
    private SettleUshopFlowCurrencyService settleUshopFlowCurrencyService;

    @Autowired
    private SettleUshopSplitMaininfoService settleUshopSplitMaininfoService;

    @Autowired
    private SettleUshopSplitCurrencyService splitCurrencyService;

    @Autowired
    private Producer producer;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private StoreInternalFeign storeInternalFeign;

    @Override
    public Map<String, Object> initRefundParams(String orderid) {
        Map<String, Object> refundParams = null;
        try {
            logger.error("SettleRefundServiceImpl-->initRefundParams params:::" + orderid);
            refundParams = cheetahFeign.initRefundParams(orderid);
            refundParams.put("checkstandId", refundParams.get("counterId"));
            logger.error("SettleRefundServiceImpl-->initRefundParams results:::" + JsonUtils.objectToJson(refundParams));
        } catch (Exception e) {
            logger.error("SettleRefundServiceImpl-->initRefundParams " + orderid + " fail: ", e);
            return null;
        }
        return refundParams;
    }

    @Override
    public ApiResult getStoreInfo(Map<String, Object> params) {
        String checkstandId = (String) params.get("checkstandId");
        Map<String, Object> storeParams = new HashMap<>();
        storeParams.put("counterId", checkstandId);
        storeParams.put("delflag", "1");
        logger.info("SettleRefundServiceImpl-->getStoreInfo params:::" + JsonUtils.objectToJson(storeParams));
        Map<String, Object> storeResult = storeFeign.getMerchantsId(storeParams);
        logger.info("SettleRefundServiceImpl-->getStoreInfo result:::" + JsonUtils.objectToJson(storeResult));
        String ruleId;
        String ysUserState;
        Map<String, Object> result = new HashMap<>();
        if (MapUtils.isNotEmpty(storeResult)) {
            ruleId = (String) storeResult.get("ruleId");
            ysUserState = (String) storeResult.get("ysUserState");//商户注册类型：1：为一清商户 其他为非一清
            result.put("ruleId", ruleId);
            result.put("ysUserState", ysUserState);
            result.put("storeId", storeResult.get("ysUserCode"));
            result.put("operateMan", storeResult.get("operateMan"));
            result.put("operateTel", storeResult.get("operateTel"));
            return ApiResult.success(result);
        } else {
            logger.info("OrderSettlementServiceImpl-->createOrederSettle storeResult is null");
            return ApiResult.failure(ApiResultCode.FAILURE, "获取门店ID失败");
        }
    }

    @Override
    public ApiResult checkRefund(Map<String, Object> params) {
        String orderId = (String) params.get(SettleUshopRefundSearchConstants.SEARCH_ORDERID);
        logger.error("SettleRefundServiceImpl-->checkRefund " + orderId + " params:::" + JsonUtils.objectToJson(params));
        boolean checkFlag = RefundParamsCheckUtils.checkRefundParams(params);
        Map<String, Object> resultMap = new HashMap();
        if (!checkFlag) {
            logger.error("SettleRefundServiceImpl-->checkRefund " + orderId + " check params fail");
            return ApiResult.failure(ApiResultCode.PARAMNULL.code(), ApiResultCode.PARAMNULL.message());
        }
        try {
            //校验退款密码是否正确
            String refundPwd = (String) params.get("refundPwd");
            refundPwd = MD5Utils.encrypt(refundPwd);
            logger.error("SettleRefundServiceImpl-->checkRefund " + orderId + " orderInfo params:::" + orderId);
            Map orderInfo = orderFeign.orderInfo(orderId);
            logger.error("SettleRefundServiceImpl-->checkRefund " + orderId + " orderInfo result:::" + JsonUtils.objectToJson(orderInfo));
            if (MapUtils.isEmpty(orderInfo)) {
                logger.error("SettleRefundServiceImpl-->checkRefund fail 该订单:" + orderId + " 获取订单信息失败");
                return ApiResult.failure(ApiResultCode.REFUND_FINSHED_ERROR.code(), "获取订单信息失败");
            }
            resultMap.put("orderInfo", orderInfo);
            String counterId = (String) orderInfo.get("counterId");
            //订单金额，与前端传的退款金额做比对
            double orderPrice = (double) orderInfo.get("orderPrice");
            BigDecimal orderAmount = new BigDecimal(StringUtils.isEmpty(Double.toString(orderPrice)) ? "0.00" : Double.toString(orderPrice)).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            logger.error("SettleRefundServiceImpl-->checkRefund " + orderId + " virtualAccountPassword params:::" + counterId);
            ApiResult virtualAccountResult = storeFeign.virtualAccountPassword(counterId);
            logger.error("SettleRefundServiceImpl-->checkRefund " + orderId + " virtualAccountPassword result:::" + JsonUtils.objectToJson(virtualAccountResult));
            if (null == virtualAccountResult || ApiResultCode.FAILURE.code().equals(virtualAccountResult.getCode())) {
                logger.error("SettleRefundServiceImpl-->checkRefund fail 该订单:" + orderId + " 获取商户退款密码失败");
                return ApiResult.failure(ApiResultCode.REFUND_GETREFUNDPWD_ERROR.code(), ApiResultCode.REFUND_GETREFUNDPWD_ERROR.message());
            }
            String pwd = (String) virtualAccountResult.getResult();
            if (StringUtils.isEmpty(pwd)) {
                logger.error("SettleRefundServiceImpl-->checkRefund fail 该订单:" + orderId + " 获取商户退款密码失败 pwd is null");
                return ApiResult.failure(ApiResultCode.REFUND_GETREFUNDPWD_ERROR.code(), ApiResultCode.REFUND_GETREFUNDPWD_ERROR.message());
            }
            logger.error("SettleRefundServiceImpl-->checkRefund compare pwd " + orderId + " refundPwd:" + refundPwd);
            if (!pwd.equals(refundPwd)) {
                logger.error("SettleRefundServiceImpl-->checkRefund fail 该订单:" + orderId + " 退款密码错误");
                return ApiResult.failure(ApiResultCode.REFUND_REFUNDPWD_ERROR.code(), ApiResultCode.REFUND_REFUNDPWD_ERROR.message());
            }
            //验证是否存在退款单
            String refundRedisKey = RedisKeyEnumConstants.ENUM_SETTLE_REFUND + orderId;
            if (redisUtils.isHasKey(refundRedisKey)) {
                logger.error("SettleRefundServiceImpl-->checkRefund fail 该订单:" + orderId + "已存在退款单");
                return ApiResult.failure(ApiResultCode.REFUND_FINSHED_ERROR.code(), ApiResultCode.REFUND_FINSHED_ERROR.message());
            }
            //将mq信息存入redis，供去重判断使用
            boolean haskey = redisUtils.setIfAbsent(refundRedisKey, orderId, 180);
            if (!haskey) {
                logger.error("SettleRefundServiceImpl-->checkRefund fail 该订单:" + orderId + "redisKey插入失败");
                return ApiResult.failure(ApiResultCode.REFUND_FINSHED_ERROR.code(), ApiResultCode.REFUND_FINSHED_ERROR.message());
            }
            //校验支付单信息
            logger.error("SettleRefundServiceImpl-->checkRefund getPayInfoByOrderId params:::" + orderId);
            Map<String, String> payInfo = payFeign.getPayInfoByOrderId(orderId);
            logger.error("SettleRefundServiceImpl-->checkRefund getPayInfoByOrderId " + orderId + " result:::" + JsonUtils.objectToJson(payInfo));
            String payId = payInfo.get("id");
            resultMap.put("payId", payId);
            String payType = payInfo.get("payType");
            resultMap.put("payType", payType);
            logger.error("SettleRefundServiceImpl-->checkRefund " + orderId + " 退款类型 payType:" + payType);

            //只有是够样优店的订单且是现金支付才调用用户中心查询积分余额是否够扣减积分,
            //000、002--够样优店,001--优惠买单
            int orderType = checkOrderType(orderId);
            if (OrderTypeEnumConstants.UNKNOW_CODE == orderType) {
                logger.error("SettleRefundServiceImpl-->checkRefund " + orderId + " 未知订单类型，退款失败");
                return ApiResult.failure(ApiResultCode.FAILURE.code(), "未知订单类型，退款失败");
            }

            if (OrderTypeEnumConstants.GYYD_CODE == (orderType) &&
                    (!PayInfoEnumConstants.ENUM_PAYTYPE_BAL.equals(payType) || !PayInfoEnumConstants.ENUM_PAYTYPE_CUR.equals(payType))) {
                String customerId = (String) orderInfo.get("customerId");
                logger.error("SettleRefundServiceImpl-->checkRefund " + orderId + " currencyFeign params:::" + customerId);
                ApiResult currencyInfo = currencyFeign.getCustomerCurrency(customerId);
                logger.error("SettleRefundServiceImpl-->checkRefund " + orderId + " currencyFeign result:::" + JsonUtils.objectToJson(currencyInfo));
                Double useCurrency = (Double) currencyInfo.get("useCurrency");
                BigDecimal customerCurrency = new BigDecimal(useCurrency.toString()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
                String splitCustomerCurrency = splitCurrencyService.getByOrderId(orderId);
                BigDecimal splitCurrency = new BigDecimal(splitCustomerCurrency).setScale(2, BigDecimal.ROUND_HALF_DOWN);
                if (customerCurrency.compareTo(splitCurrency) < 0) {
                    logger.error("SettleRefundServiceImpl-->checkRefund " + orderId + " 该用户当前积分不够退款积分额度 customerCurrency" + customerCurrency + ",splitCurrency:" + splitCurrency);
                    return ApiResult.failure(ApiResultCode.FAILURE.code(), "该用户当前积分额度不够该笔订单积分退款");
                }
            }

            //校验订单支付时间，只能退当日订单
            String orderTime = payInfo.get("gmtCreate");
            logger.error("SettleRefundServiceImpl.checkRefund()---获取到下单时间的格式:" +orderTime);
            /*获取退款账期*/
            ApiResult apiResult = storeInternalFeign.getPaymentDayByCounterId(counterId);
            logger.error("SettleRefundServiceImpl.checkRefund()---通过收银台id获取商户中心的退款账期参数信息为:" + apiResult);
            /*解析参数*/
            String accountDateStr = (String) apiResult.getResult();
            logger.error("SettleRefundServiceImpl.checkRefund()---通过收银台id获取商户中心的退款账期参数信息为:" + accountDateStr);
            int accountDate = Integer.parseInt(accountDateStr);
            boolean orderInfoFlag = compareOrderTime(orderId, orderTime, accountDate);
            if (!orderInfoFlag) {
                return ApiResult.failure(ApiResultCode.FAILURE.code(), "申请退款订单超出设定期限:"+accountDate+"天，不允许退款");
            }
            String payChannel = payInfo.get("payChannel");
            //如果支付渠道是银盛且不是余额支付或者不是积分支付才做银盛预分账查询，只有预分账成功才可以退款
            if (PayInfoEnumConstants.ENUM_PAYCHANNEL_YS.equals(payChannel) &&
                    (!PayInfoEnumConstants.ENUM_PAYTYPE_CUR.equals(payType) || !PayInfoEnumConstants.ENUM_PAYTYPE_BAL.equals(payType))) {
                //查询银盛订单信息是否为已分账状态
                Map<String, Object> ysPreAccountQueryParams = initYsPreAccountQueryParams(orderId);
                String splitRequestReceiptResult = ysFeign.splitRequestReceipt(ysPreAccountQueryParams);
                Map<String, Object> splitRequestReceipt = JsonUtils.jsonToMap(splitRequestReceiptResult);
//                Map<String,Object> splitRequestReceipt = new HashMap<>();
//                splitRequestReceipt.put("division_status_code","01");
                logger.error("SettleRefundServiceImpl-->checkRefund splitRequestReceiptResult:::" + splitRequestReceiptResult);
                //00分账成功、02预分账成功
                if (!"00".equals(splitRequestReceipt.get("division_status_code")) && !"02".equals(splitRequestReceipt.get("division_status_code"))) {
                    logger.error("SettleRefundServiceImpl-->checkRefund " + orderId + " fail 预分账不成功，不能退款");
                    redisUtils.delKey(refundRedisKey);
                    return ApiResult.failure(ApiResultCode.PRESPLIT_ERROR.code(), ApiResultCode.PRESPLIT_ERROR.message());
                }
            }
            BigDecimal payInfoAmount;
            if (PayInfoEnumConstants.ENUM_PAYTYPE_CUR.equals(payType)) {
                payInfoAmount = new BigDecimal(payInfo.get("payCur")).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            } else if (PayInfoEnumConstants.ENUM_PAYTYPE_BAL.equals(payType)) {
                payInfoAmount = new BigDecimal(payInfo.get("payBalance")).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            } else {
                payInfoAmount = new BigDecimal(payInfo.get("payMoney")).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            }
            resultMap.put("payInfoAmount", payInfoAmount);
            BigDecimal amount = new BigDecimal((String) params.get("amount"));
            amount = amount.setScale(2, BigDecimal.ROUND_HALF_DOWN);
            if (amount.compareTo(orderAmount) != 0) {
                logger.error("SettleRefundServiceImpl-->checkRefund " + orderId + " fail：退款金额与支付单金额不符，" +
                        "orderAmount：" + orderAmount + ",amount" + amount);
                return ApiResult.failure(ApiResultCode.REASON_TRADE_REFUND_FEE_ERR);
            }
        } catch (Exception e) {
            logger.error("SettleRefundServiceImpl-->checkRefund " + orderId + " fail ", e);
            return ApiResult.failure(ApiResultCode.PARAMERROR);
        }

        return ApiResult.success(resultMap);
    }

    @Override
    public Map<String, Object> createRefund(Map<String, Object> params) {
        logger.error("SettleRefundServiceImpl-->createRefund start params:::" + JsonUtils.objectToJson(params));
        SettleUshopRefundDO refundDO = new SettleUshopRefundDO();
        String refundId = sysconfigFeign.getRefundId();
        refundDO.setId(refundId);
        refundDO.setOrderId((String) params.get(OrderUshopSearchConstants.SEARCH_ORDERID));
        refundDO.setPayChannel((String) params.get(SettleUshopRefundSearchConstants.SEARCH_PAYCHANNEL));
        String refundAmount = params.get("amount") == null ? "0.0" : (String) params.get("amount");
        refundDO.setRefundAmount(new BigDecimal(refundAmount));
        refundDO.setRefundRule((String) params.get(SettleUshopRefundSearchConstants.SEARCH_REFUNDRULE));
        refundDO.setRefundReason((String) params.get(SettleUshopRefundSearchConstants.SEARCH_REFUNDREASON));
        refundDO.setStatus(SettleUshopRefundEnumConstants.ENUM_STATUS_GOING);
        refundDO.setIsDelete(SettleUshopRefundEnumConstants.ENUM_ISDELETE_UNDEL);
        refundDO.setGmtCreate(new Date());
        Map<String, Object> resultMap = new HashMap();
        resultMap.put("refundId", refundId);
        int countRefund;
        try {
            countRefund = settleUshopRefundService.save(refundDO);
        } catch (Exception e) {
            logger.error("SettleRefundServiceImpl-->createRefund fail", e);
            resultMap.put("createFlag", false);
            return resultMap;
        }
        if (countRefund > 0) {
            logger.info("SettleRefundServiceImpl-->createRefund succes count:" + countRefund);
            resultMap.put("createFlag", true);
            return resultMap;
        } else {
            logger.info("SettleRefundServiceImpl-->createRefund fail count:" + countRefund);
            resultMap.put("createFlag", false);
            return resultMap;
        }
    }


    @Override
    public ApiResult separateRefund(Map<String, Object> params) {
        Map<String, Object> SeparateRefundParams = initSeparateRefundParams(params);
        String outTradeNo = (String) params.get("out_trade_no");
        try {
            logger.info("SettleRefundServiceImpl-->separateRefund start params:::" + SeparateRefundParams);
            ApiResult result = ysFeign.routingRefundRequest(SeparateRefundParams);
            SettleUshopSplitRluesDO splitRluesDO = (SettleUshopSplitRluesDO) SeparateRefundParams.get("splitRluesDO");
            result.setResult(splitRluesDO);
            logger.info("SettleRefundServiceImpl-->separateRefund outTradeNo:" + outTradeNo + " result:::" + JsonUtils.objectToJson(result));
            return result;
        } catch (Exception e) {
            logger.error("SettleRefundServiceImpl-->separateRefund fail", e);
            return ApiResult.failure();
        }
    }

    @Override
    public ApiResult balanceRefund(Map<String, Object> params) {
        String orderId = (String) params.get(SettleUshopRefundSearchConstants.SEARCH_ORDERID);
        Map<String, Object> balanceRefundParams = initBalanceRefundParams(params);
        try {
            logger.error("SettleRefundServiceImpl-->balanceRefund " + orderId + " start params:::" + JsonUtils.objectToJson(balanceRefundParams));
            ApiResult result = financialFeign.balanceRefund(balanceRefundParams);
            logger.error("SettleRefundServiceImpl-->balanceRefund " + orderId + " result:::" + JsonUtils.objectToJson(result));
            SettleUshopSplitRluesDO splitRluesDO = (SettleUshopSplitRluesDO) balanceRefundParams.get("splitRluesDO");
            result.setResult(splitRluesDO);
            return result;
        } catch (Exception e) {
            logger.error("SettleRefundServiceImpl-->balanceRefund fail", e);
            return ApiResult.failure();
        }
    }

    @Override
    public ApiResult integralRefund(Map<String, Object> params) {
        String orderId = (String) params.get(SettleUshopRefundSearchConstants.SEARCH_ORDERID);
        Map<String, Object> integralRefundParams = initIntegralRefundParams(params);
        try {
            logger.error("SettleRefundServiceImpl-->integralRefund " + orderId + " start params:::" + JsonUtils.objectToJson(integralRefundParams));
            ApiResult result = financialFeign.integralRefund(integralRefundParams);
            logger.error("SettleRefundServiceImpl-->integralRefund " + orderId + " result:::" + JsonUtils.objectToJson(result));
            SettleUshopSplitRluesDO splitRluesDO = (SettleUshopSplitRluesDO) integralRefundParams.get("splitRluesDO");
            result.setResult(splitRluesDO);
            return result;
        } catch (Exception e) {
            logger.error("SettleRefundServiceImpl-->integralRefund fail", e);
            return ApiResult.failure();
        }
    }

    //生成积分退款参数
    private Map<String, Object> initIntegralRefundParams(Map<String, Object> params) {
        String orderId = (String) params.get(SettleUshopRefundSearchConstants.SEARCH_ORDERID);
        String ruleId = settleUshopSplitMaininfoService.getRuleIdByOrderId(orderId);
        logger.error("SettleRefundServiceImpl-->initIntegralRefundParams getSettleSplitRules ruleId:" + ruleId);
        SettleUshopSplitRluesDO splitRluesDO = getSettleSplitRules(ruleId);
        Map orderInfo = (Map) params.get("orderInfo");
        logger.error("SettleRefundServiceImpl-->initIntegralRefundParams " + orderId + " orderInfo:" + JsonUtils.objectToJson(orderInfo));
        String customerId = (String) orderInfo.get("customerId");
        //积分退款交易号
        String outTradeNo = (String) params.get("outTradeNo");
        //支付单号
        String payId = (String) params.get("payId");
        //退款总金额
        BigDecimal refundAmount = (BigDecimal) params.get("payInfoAmount");
        //退款原因
        String refundReason = (String) params.get("refundReason");
        //获取token
        String Authorization = FilterContextHandler.getToken();
        //参数拼装
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("customerId", customerId);
        returnMap.put("payId", payId);
        returnMap.put("prePayNo", outTradeNo);
        returnMap.put("Authorization", Authorization);
        returnMap.put("backCurrency", refundAmount);
        returnMap.put("refundReason", refundReason);
        logger.error("SettleRefundServiceImpl-->initIntegralRefundParams " + orderId + " return:" + JsonUtils.objectToJson(returnMap));
        returnMap.put("splitRluesDO", splitRluesDO);
        return returnMap;
    }

    //生成余额退款参数
    private Map<String, Object> initBalanceRefundParams(Map<String, Object> params) {
        String orderId = (String) params.get(SettleUshopRefundSearchConstants.SEARCH_ORDERID);
        String ruleId = settleUshopSplitMaininfoService.getRuleIdByOrderId(orderId);
        logger.error("SettleRefundServiceImpl-->initBalanceRefundParams getSettleSplitRules ruleId:" + ruleId);
        SettleUshopSplitRluesDO splitRluesDO = getSettleSplitRules(ruleId);
        Map orderInfo = (Map) params.get("orderInfo");
        logger.error("SettleRefundServiceImpl-->initBalanceRefundParams " + orderId + " orderInfo:" + JsonUtils.objectToJson(orderInfo));
        String customerId = (String) orderInfo.get("customerId");
        //获取用户id
        logger.error("SettleRefundServiceImpl-->initBalanceRefundParams " + orderId + " getCustomerInfo params:::" + customerId);
        ApiResult customerResult = customerFeign.getCustomerInfo(customerId);
        logger.error("SettleRefundServiceImpl-->initBalanceRefundParams " + orderId + " getCustomerInfo result:::" + JsonUtils.objectToJson(customerResult));
        if (null == customerResult || !ApiResultCode.SUCCESS.code().equals(customerResult.getCode())) {
            logger.error("SettleRefundServiceImpl-->initBalanceRefundParams " + orderId + "  fail :getcustomerId fail");
        }
        Map<String, Object> customer = (Map<String, Object>) customerResult.getResult();
        String customerUuid = (String) customer.get("mainUuid");
        //余额退款交易号
        String outTradeNo = (String) params.get("outTradeNo");
        //退款总金额
        BigDecimal refundAmount = (BigDecimal) params.get("payInfoAmount");
        //退款原因
        String refundReason = (String) params.get("refundReason");

        //参数拼装
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("customerUuid", customerUuid);
        returnMap.put("prePayNo", outTradeNo);
        returnMap.put("payMoney", refundAmount);
        returnMap.put("refundReason", refundReason);
        returnMap.put("splitRluesDO", splitRluesDO);
        logger.error("SettleRefundServiceImpl-->initBalanceRefundParams " + orderId + " return:" + JsonUtils.objectToJson(returnMap));
        return returnMap;
    }

    //生成分账退款参数
    private Map<String, Object> initSeparateRefundParams(Map<String, Object> params) {
        String orderId = (String) params.get(SettleUshopRefundSearchConstants.SEARCH_ORDERID);
        String ruleId = settleUshopSplitMaininfoService.getRuleIdByOrderId(orderId);
        logger.error("SettleRefundServiceImpl-->initSeparateRefundParams getSettleSplitRules ruleId:" + ruleId);
        SettleUshopSplitRluesDO splitRluesDO = getSettleSplitRules(ruleId);
        logger.error("SettleRefundServiceImpl-->initSeparateRefundParams getSettleSplitRules:" + JsonUtils.objectToJson(splitRluesDO));
        BigDecimal amount = new BigDecimal((String) params.get("amount"));
        BigDecimal storeAmount = amount.multiply(splitRluesDO.getCustomerRatio()).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal plantformAmount = amount.multiply(splitRluesDO.getPlatformRatio()).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal virtualAmount = amount.multiply(splitRluesDO.getVirtualRatio()).setScale(2, BigDecimal.ROUND_HALF_UP);
        //银盛交易号
        String outTradeNo = (String) params.get("outTradeNo");
        //退款总金额
        BigDecimal refundAmount = amount.setScale(2, BigDecimal.ROUND_HALF_UP);
        //退款原因
        String refundReason = (String) params.get("refundReason");

        //返回参数拼装
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("out_trade_no", outTradeNo);
        returnMap.put("refund_amount", refundAmount);
        returnMap.put("refund_reason", refundReason);
        returnMap.put("storeId", params.get("ysStoreId"));
        returnMap.put("storeAmount", storeAmount);
        returnMap.put("plantformAmount", plantformAmount);
        returnMap.put("virtualAmount", virtualAmount);
        logger.error("SettleRefundServiceImpl-->initSeparateRefundParams return:" + JsonUtils.objectToJson(returnMap));
        returnMap.put("splitRluesDO", splitRluesDO);
        return returnMap;
    }

    private SettleUshopSplitRluesDO getSettleSplitRules(String ruleId) {
        SettleUshopSplitRluesDO rluesDO = settleUshopSplitRluesService.get(ruleId);
        return rluesDO;
    }

    @Override
    public ApiResult createFlowInfo(Map<String, Object> params) {
        try {
            logger.error("SettleRefundServiceImpl-->createFlowInfo start params:::" + JsonUtils.objectToJson(params));
            Map<String, Object> flowMap = initFlowParams(params);
            SettleUshopFlowStoreDO flowStoreDO = (SettleUshopFlowStoreDO) flowMap.get("flowStoreDO");
            SettleUshopFlowPlantformDO flowPlantformDO = (SettleUshopFlowPlantformDO) flowMap.get("flowPlantformDO");
            SettleUshopFlowCurrencyDO flowCurrencyDO = (SettleUshopFlowCurrencyDO) flowMap.get("flowCurrencyDO");
            int storeCount = settleUshopFlowStoreService.save(flowStoreDO);
            int plantformCount = settleUshopFlowPlantformService.save(flowPlantformDO);
            int currencyCount = settleUshopFlowCurrencyService.save(flowCurrencyDO);
            BigDecimal storeAmount = flowStoreDO.getAmount();
            if (storeCount > 0 && plantformCount > 0 && currencyCount > 0) {
                logger.error("生成退款流水信息成功");
                Map<String, Object> resultMap = new HashMap();
                resultMap.put("storeAmount", storeAmount);
                return ApiResult.success(resultMap);
            }
            logger.error("SettleRefundServiceImpl-->createFlowInfo 生成流水信息失败 storeCount:" + storeCount + ",plantformCount:" +
                    +plantformCount + ",currencyCount:" + currencyCount);
            return ApiResult.failure("生成流水信息失败");
        } catch (Exception e) {
            logger.error("SettleRefundServiceImpl-->createFlowInfo fail", e);
            return ApiResult.failure("生成流水信息失败");
        }

    }

    @Override
    public ApiResult freezeOrUnFreezeVirtualMoney(Map<String, Object> params) {
        String payType = (String) params.get("payType");
        String orderId = (String) params.get(SettleUshopRefundSearchConstants.SEARCH_ORDERID);
        String ruleId = settleUshopSplitMaininfoService.getRuleIdByOrderId(orderId);
        String storeAmount = settleUshopSplitMaininfoService.getStoreAmountByOrderId(orderId);
        String operType = (String) params.get("operType");
        logger.error("SettleRefundServiceImpl-->freezeOrUnFreezeVirtualMoney getSettleSplitRules ruleId:" + ruleId);
        SettleUshopSplitRluesDO splitRluesDO = getSettleSplitRules(ruleId);
        logger.error("SettleRefundServiceImpl-->freezeOrUnFreezeVirtualMoney getSettleSplitRules:" + JsonUtils.objectToJson(splitRluesDO));
        Map<String, Object> freezeParams = new HashMap<>();
        //直接拿商户分账时的进账金额
        BigDecimal operAmount = new BigDecimal(StringUtils.isEmpty(storeAmount) ? "0.00" : storeAmount).setScale(2, BigDecimal.ROUND_HALF_DOWN);
        freezeParams.put("storeUuid", params.get("storeId"));
        BigDecimal operIntegralAmount;
        BigDecimal operBalanceAmount;
        BigDecimal operCashAmount;
        if (PayInfoEnumConstants.ENUM_PAYTYPE_BAL.equals(payType)) {  //余额退款
            operBalanceAmount = operAmount;
            operIntegralAmount = new BigDecimal("0.00");
            operCashAmount = new BigDecimal("0.00");
        } else if (PayInfoEnumConstants.ENUM_PAYTYPE_CUR.equals(payType)) {  //积分支付
            operIntegralAmount = operAmount;
            operBalanceAmount = new BigDecimal("0.00");
            operCashAmount = new BigDecimal("0.00");
        } else {  //现金支付
            operCashAmount = operAmount;
            operBalanceAmount = new BigDecimal("0.00");
            operIntegralAmount = new BigDecimal("0.00");
        }
        String businessType;
        //根据订单号的第四位到第六位的三位数区分订单类型，够样优店和优惠买单两种类型匹配不同类型分账规则
        boolean curNotify = orderId.substring(4, 7).equals("000");
        if (curNotify) {
            //够样优店
            businessType = StoreVirtualOperConstants.OPTIMAL_STORE_ORDER_REFUND;
        } else {
            //优惠买单
            businessType = StoreVirtualOperConstants.PREFERENTIAL_ORDER_REFUND;
        }
        freezeParams.put("operBalanceAmount", operBalanceAmount);
        freezeParams.put("operIntegralAmount", operIntegralAmount);
        freezeParams.put("operCashAmount", operCashAmount);
        operAmount = operBalanceAmount.add(operIntegralAmount).add(operCashAmount);
        freezeParams.put("operAmount", operAmount);
        freezeParams.put("operType", params.get("operType"));
        freezeParams.put("businessType", businessType);
        freezeParams.put("customerUuid", params.get("storeId"));
        freezeParams.put("orderNo", params.get("orderId"));
        String description;
        if (StoreVirtualOperConstants.OUT_FREEZE_MONEY.equals(operType)) {
            description = String.format(StoreFlowDescription.REFUD_FAIL, params.get("orderId").toString(), operAmount.toString());
        } else {
            description = String.format(StoreFlowDescription.REFUDING, params.get("orderId").toString(), operAmount.toString());
        }
        freezeParams.put("description", description);
        logger.error("SettleRefundServiceImpl--> freezeOrUnFreezeVirtualMoney params:::" + JsonUtils.objectToJson(freezeParams));
        Map<String, Object> freezeResult = storeFeign.freezeOrUnFreezeVirtualMoney(freezeParams);
        logger.error("SettleRefundServiceImpl--> freezeOrUnFreezeVirtualMoney result:::" + JsonUtils.objectToJson(freezeResult));
        if (!ApiResultCode.SUCCESS.code().equals(freezeResult.get("code"))) {
            logger.error("SettleRefundServiceImpl--> freezeOrUnFreezeVirtualMoney fail");
            return ApiResult.failure("冻结商户资金失败");
        }
        return ApiResult.success(operAmount);
    }

    public Map<String, Object> initFlowParams(Map<String, Object> params) {
        String ruleId = (String) params.get(SettleUshopRefundSearchConstants.SEARCH_REFUNDRULE);
        //查询分账规则，生成反向流水
//        SettleUshopSplitRluesDO splitRluesDO = settleUshopSplitRluesService.get(ruleId);
        SettleUshopSplitRluesDO splitRluesDO = (SettleUshopSplitRluesDO) params.get("splitRluesDO");
        String flowId = sysconfigFeign.getFlowId();
        String refundId = (String) params.get("refundId");
        String paramsAmount = params.get(SettleUshopFlowStoreSearchConstants.SEARCH_AMOUNT) == null ? "0.00" : (String) params.get(SettleUshopFlowStoreSearchConstants.SEARCH_AMOUNT);
        BigDecimal amount = new BigDecimal(paramsAmount);
        //商户退款流水
        SettleUshopFlowStoreDO flowStoreDO = new SettleUshopFlowStoreDO();
        flowStoreDO.setId(flowId);
        flowStoreDO.setFlowType(SettleUshopFlowStoreEnumConstants.ENUM_FLOWTYPE_REFUND);
        flowStoreDO.setStoreId((String) params.get(SettleUshopFlowStoreSearchConstants.SEARCH_STOREID));
        flowStoreDO.setCheckstandId((String) params.get(SettleUshopFlowStoreSearchConstants.SEARCH_CHECKSTANDID));
        flowStoreDO.setExternalId(refundId);
        String storeAmount = "-" + splitRluesDO.getCustomerRatio().multiply(amount);
        flowStoreDO.setAmount(new BigDecimal(storeAmount));
        flowStoreDO.setNote(CommonConstants.ENUM_REFUND_NODE);
        flowStoreDO.setIsDelete(SettleUshopFlowStoreEnumConstants.ENUM_ISDELETE_UNDEL);
        flowStoreDO.setGmtCreate(new Date());
        flowStoreDO.setOperateMan((String) params.get("operateMan"));
        flowStoreDO.setOperateTel((String) params.get("operateTel"));

        //平台退款流水
        SettleUshopFlowPlantformDO flowPlantformDO = new SettleUshopFlowPlantformDO();
        flowPlantformDO.setId(flowId);
        flowPlantformDO.setExternalId(refundId);
        flowPlantformDO.setFlowType(SettleUshopFlowPlantformEnumConstants.ENUM_FLOWTYPE_REFUND);
        String plantformAmount = "-" + splitRluesDO.getPlatformRatio().multiply(amount);
        flowPlantformDO.setAmount(new BigDecimal(plantformAmount));
        flowPlantformDO.setNote(CommonConstants.ENUM_REFUND_NODE);
        flowPlantformDO.setIsDelete(SettleUshopFlowPlantformEnumConstants.ENUM_ISDELETE_UNDEL);
        flowPlantformDO.setGmtCreate(new Date());

        //积分退款流水
        SettleUshopFlowCurrencyDO flowCurrencyDO = new SettleUshopFlowCurrencyDO();
        flowCurrencyDO.setId(flowId);
        flowCurrencyDO.setFlowType(SettleUshopFlowCurrencyEnumConstants.ENUM_FLOWTYPE_REFUND);
        flowCurrencyDO.setExternalId(refundId);
        flowCurrencyDO.setCustomerId((String) params.get(SettleUshopFlowCurrencySearchConstants.SEARCH_CUSTOMERID));
        String currencyAmount = "-" + splitRluesDO.getVirtualRatio().multiply(amount);
        flowCurrencyDO.setAmount(new BigDecimal(currencyAmount));
        flowCurrencyDO.setNote(CommonConstants.ENUM_REFUND_NODE);
        flowCurrencyDO.setIsDelete(SettleUshopFlowCurrencyEnumConstants.ENUM_ISDELETE_UNDEL);
        flowCurrencyDO.setGmtCreate(new Date());

        //组装返回参数
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("flowStoreDO", flowStoreDO);
        resultMap.put("flowPlantformDO", flowPlantformDO);
        resultMap.put("flowCurrencyDO", flowCurrencyDO);
        logger.error("SettleRefundServiceImpl-->initFlowParams return:::" + JsonUtils.objectToJson(resultMap));
        return resultMap;
    }

    //分账完毕通知商户中心MQ
    @Override
    public void sendStoreMessage(Map<String, Object> params) {
        //初始化消息
        String msgBody = JsonUtils.objectToJson(params);
        Message msg = new Message(SettleMQConfig.STORETOPIC, SettleMQConfig.NOTIFYSTORE_TAG, msgBody.getBytes());
        logger.error("SettleUshopRefundController-->sendStoreMessage start! params:::" + JsonUtils.objectToJson(params));
        try {
            SendResult sendResult = producer.send(msg);
            assert sendResult != null;
            logger.error("SettleUshopRefundController-->sendStoreMessage Send message success! Topic is:"
                    + SettleMQConfig.STORETOPIC + " msgId is: " + sendResult.getMessageId());
        } catch (ONSClientException e) {
            // 消息发送失败，需要进行重试处理，可重新发送这条消息或持久化这条数据进行补偿处理
            logger.error("SettleUshopRefundController-->sendStoreMessage Send mq message failed! Topic is:" + SettleMQConfig.TOPIC, e);
            e.printStackTrace();
        }
    }

    //分账完毕通知商户中心MQ
    @Override
    public void sendOrderMessage(Map<String, Object> params, String type) {
        String orderId = (String) params.get(SettleUshopRefundSearchConstants.SEARCH_ORDERID);
        //初始化消息
        String msgBody = JsonUtils.objectToJson(params);
        try {
            String orderTags;
            if (OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDING.equals(type)) {
                orderTags = SettleMQConfig.ORDER_TAG_REFUNDING;
            } else if (OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDED.equals(type)) {
                orderTags = SettleMQConfig.ORDER_TAG_REFUNDED;
            } else {
                orderTags = SettleMQConfig.ORDER_TAG_REFUNDFAIL;
            }
            Message msg = new Message(SettleMQConfig.ORDERTOPIC, orderTags, msgBody.getBytes());
            logger.error("SettleUshopRefundController-->sendOrderMessage start! params:::" + JsonUtils.objectToJson(params));
            SendResult sendResult = producer.send(msg);
            assert sendResult != null;
            logger.error("SettleUshopRefundController-->sendOrderMessage " + orderId + " Send message success! Topic is:"
                    + SettleMQConfig.ORDERTOPIC + ",Tag:" + orderTags + " msgId is: " + sendResult.getMessageId());
        } catch (ONSClientException e) {
            // 消息发送失败，需要进行重试处理，可重新发送这条消息或持久化这条数据进行补偿处理
            logger.error("SettleUshopRefundController-->sendOrderMessage " + orderId + " Send mq message failed! Topic is:" + SettleMQConfig.TOPIC, e);
            e.printStackTrace();
        }
    }

    @Override
    public Map<String, Object> initChangeStoreVirtualParams(Map<String, Object> params) {
        String orderId = (String) params.get("orderId");
        String amount = (String) params.get("amount");
        Map<String, Object> freezeParams = new HashMap<>();
        try {
            String payType = (String) params.get("payType");
            freezeParams.put("storeUuid", params.get("storeId"));
            freezeParams.put("orderNo", params.get("orderId"));
            String storeAmount = settleUshopSplitMaininfoService.getStoreAmountByOrderId(orderId);
            BigDecimal operAmount = new BigDecimal(StringUtils.isEmpty(storeAmount) ? "0.00" : storeAmount).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            freezeParams.put("operFreezeAmount", operAmount);
            freezeParams.put("customerUuid", params.get("storeId"));
            String description = String.format(StoreFlowDescription.REFUD_SUCC, params.get("orderId").toString(), amount);
            freezeParams.put("description", description);
            freezeParams.put("operType", StoreVirtualOperConstants.OUT_FREEZE_MONEY);
            String businessType;
            //根据订单号的第四位到第六位的三位数区分订单类型，够样优店和优惠买单两种类型匹配不同类型分账规则
            boolean curNotify = orderId.substring(4, 7).equals("000");
            if (curNotify) {
                //够样优店
                businessType = StoreVirtualOperConstants.OPTIMAL_STORE_ORDER_REFUND;
            } else {
                //优惠买单
                businessType = StoreVirtualOperConstants.PREFERENTIAL_ORDER_REFUND;
            }
            freezeParams.put("businessType", businessType);
            BigDecimal operIntegralAmount;
            BigDecimal operBalanceAmount;
            BigDecimal operCashAmount;
            if (PayInfoEnumConstants.ENUM_PAYTYPE_BAL.equals(payType)) {  //余额退款
                operBalanceAmount = operAmount;
                operIntegralAmount = new BigDecimal("0.00");
                operCashAmount = new BigDecimal("0.00");
            } else if (PayInfoEnumConstants.ENUM_PAYTYPE_CUR.equals(payType)) {  //积分支付
                operIntegralAmount = operAmount;
                operBalanceAmount = new BigDecimal("0.00");
                operCashAmount = new BigDecimal("0.00");
            } else {  //现金支付
                operCashAmount = operAmount;
                operBalanceAmount = new BigDecimal("0.00");
                operIntegralAmount = new BigDecimal("0.00");
            }
            freezeParams.put("operCashAmount", operCashAmount);
            freezeParams.put("operBalanceAmount", operBalanceAmount);
            freezeParams.put("operIntegralAmount", operIntegralAmount);
        } catch (Exception e) {
            logger.error("SettleRefundServiceImpl-->initChangeStoreVirtualParams " + orderId + " fail:", e);
        }
        return freezeParams;
    }

    private Map<String, Object> initYsPreAccountQueryParams(String orderId) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> returnMap = new HashMap<>();
        //获取在银盛开设的平台账号
        try {
            String srcUsercode = sysconfigFeign.getYSPlanformCode();
            //获取支付单号
            Map<String, Object> payInfo = payFeign.getPayInfoByOrderId(orderId);
            resultMap.put("src_usercode", srcUsercode);
            String outTradeNo = (String) payInfo.get("outTradeNo");
            resultMap.put("out_trade_no", outTradeNo);
        } catch (Exception e) {
            logger.error("SettleRefundServiceImpl-->initYsPreAccountQueryParams fail:", e);
        }
        returnMap.put("biz_content", JsonUtils.beanToJson(resultMap));
        logger.error("SettleRefundServiceImpl-->initYsPreAccountQueryParams orderId:"
                + orderId + " result:::" + JsonUtils.objectToJson(returnMap));
        return returnMap;
    }

    /**
     * @param orderId
     * @param orderTime
     * @param accountDate 退款账期天数
     * @return boolean
     * @Author cuich
     * @Date 2019/8/20 16:10
     **/
    private boolean compareOrderTime(String orderId, String orderTime, int accountDate) {
        try {
            boolean flag;
            /*获取订单支付时间格式化*/
            SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", java.util.Locale.US);
            Date orderDate = sdf.parse(orderTime);
            if (accountDate > 1) {
                logger.error("SettleRefundServiceImpl.compareOrderTime()---该商户账期超过一天,退款账期天数为:" + accountDate);
                /*n天无理由退款商户店*/
                /*将传过来的下单时间格式字符串转换String类型*/
                String createTime=DateUtils.getDateStr(orderDate);
                /*获取订单失效时间*/
                String endDateStr = DateUtils.getAfterDay(createTime, accountDate);
                logger.error("SettleRefundServiceImpl.compareOrderTime()---该笔订单失效的时间(String):" + endDateStr);
                Date endDate = DateUtils.strToDate(endDateStr);
                /*判断退款时间是否在退款账期之内， 如果在方可退款，否则失败*/
                flag = DateUtils.isEffectiveDate(new Date(), orderDate, endDate);
                if (flag) {
                    /*在有效期内可以退款*/
                    logger.error("SettleRefundServiceImpl.compareOrderTime()---在有效期内可以退款,返回状态值为:" + flag);
                } else {
                    /*超出退款账期不可退款*/
                    logger.error("SettleRefundServiceImpl.compareOrderTime()---超出退款账期不可退款,返回状态值为:" + flag);
                }
            } else {
                /*一般当天退款商户*/
                Date today = DateUtils.getTodayZeroTime();
                flag = today.before(orderDate);
                logger.error("SettleRefundServiceImpl-->compareOrderTime orderId:" + orderId + " orderDate:" + orderDate + ",today:" + today + ",compare:" + flag);
            }
            return flag;
        } catch (Exception e) {
            logger.error("SettleRefundServiceImpl-->compareOrderTime orderId:" + orderId + " fail:", e);
            return false;
        }
    }

    //通知cheetah中心数据同步
    @Override
    public void sendCheetahMessage(Map<String, Object> params) {
        String orderId = (String) params.get(SettleUshopRefundSearchConstants.SEARCH_ORDERID);
        //初始化消息
        String msgBody = JsonUtils.objectToJson(params);
        long delayTime = System.currentTimeMillis() + 1000 * 60 * 1;
        Message orderPaymentRefundMsg = new Message(SettleMQConfig.CHEETAHTOPIC, SettleMQConfig.ORDER_PAYMENT_REFUND_TAG, msgBody.getBytes());
        orderPaymentRefundMsg.setStartDeliverTime(delayTime);
        Message orderSettleMsg = new Message(SettleMQConfig.CHEETAHTOPIC, SettleMQConfig.TMP_ORDER_SETTLE_REFUND_TAG, msgBody.getBytes());
        orderSettleMsg.setStartDeliverTime(delayTime);
        Message orderPayMsg = new Message(SettleMQConfig.CHEETAHTOPIC, SettleMQConfig.TMP_ORDER_PAY_REFUND_TAG, msgBody.getBytes());
        orderPayMsg.setStartDeliverTime(delayTime);
        Message orderFlowMsg = new Message(SettleMQConfig.CHEETAHTOPIC, SettleMQConfig.TMP_ORDER_FLOW_REFUND_TAG, msgBody.getBytes());
        orderFlowMsg.setStartDeliverTime(delayTime);
        logger.error(new Date() + "SettleRefundServiceImpl-->sendCheetahMessage start! params:::" + JsonUtils.objectToJson(params));

        try {
            SendResult orderPaymentRefundSendResult = producer.send(orderPaymentRefundMsg);
            SendResult settleSendResult = producer.send(orderSettleMsg);
            SendResult paySendResult = producer.send(orderPayMsg);
            SendResult flowSendResult = producer.send(orderFlowMsg);
            assert orderPaymentRefundSendResult != null;
            logger.error(new Date() + "SettleRefundServiceImpl-->sendCheetahMessage " + orderId + " Send message success! Topic is:"
                    + SettleMQConfig.CHEETAHTOPIC + " msgId is: " + orderPaymentRefundSendResult.getMessageId());
            assert settleSendResult != null;
            logger.error(new Date() + "SettleRefundServiceImpl-->sendCheetahMessage " + orderId + " Send message success! Topic is:"
                    + SettleMQConfig.CHEETAHTOPIC + " msgId is: " + settleSendResult.getMessageId());
            assert paySendResult != null;
            logger.error(new Date() + "SettleRefundServiceImpl-->sendCheetahMessage " + orderId + " Send message success! Topic is:"
                    + SettleMQConfig.CHEETAHTOPIC + " msgId is: " + paySendResult.getMessageId());
            assert flowSendResult != null;
            logger.error(new Date() + "SettleRefundServiceImpl-->sendCheetahMessage " + orderId + " Send message success! Topic is:"
                    + SettleMQConfig.CHEETAHTOPIC + " msgId is: " + flowSendResult.getMessageId());
        } catch (ONSClientException e) {
            // 消息发送失败，需要进行重试处理，可重新发送这条消息或持久化这条数据进行补偿处理
            logger.error(new Date() + "SettleRefundServiceImpl-->sendCheetahMessage " + orderId + " Send mq message failed! Topic is:" + SettleMQConfig.CHEETAHTOPIC, e);
            e.printStackTrace();
        }
    }

    //通知用户修改积分
    @Override
    public void sendCurrencyMessage(Map<String, Object> params) {
        String orderId = (String) params.get(SettleUshopRefundSearchConstants.SEARCH_ORDERID);
        //初始化消息
        String msgBody = JsonUtils.objectToJson(params);
        Message msg = new Message(SettleMQConfig.CURRENCYTOPIC, SettleMQConfig.CURRENCY_CHANGE_INTEGRALS, msgBody.getBytes());
        logger.error(new Date() + "SettleRefundServiceImpl-->sendCurrencyMessage start! params:::" + JsonUtils.objectToJson(params));
        try {
            SendResult currencySendResult = producer.send(msg);
            assert currencySendResult != null;
            logger.error(new Date() + "SettleRefundServiceImpl-->sendCurrencyMessage " + orderId + " Send message success! Topic is:"
                    + SettleMQConfig.CURRENCYTOPIC + " msgId is: " + currencySendResult.getMessageId());
        } catch (ONSClientException e) {
            // 消息发送失败，需要进行重试处理，可重新发送这条消息或持久化这条数据进行补偿处理
            logger.error(new Date() + "SettleRefundServiceImpl-->sendCurrencyMessage " + orderId + " Send mq message failed! Topic is:" + SettleMQConfig.CURRENCYTOPIC, e);
            e.printStackTrace();
        }
    }

    private int checkOrderType(String orderId) {
        String orderSub = orderId.substring(4, 7);
        //根据订单号的第四位到第六位的三位数区分订单类型，够样优店和优惠买单两种类型匹配不同类型分账规则
        //000、002--够样优店,001--优惠买单
        if (OrderTypeEnumConstants.GYYD_CREDIT.equals(orderSub)) {
            return OrderTypeEnumConstants.GYYD_CODE;
        } else if (OrderTypeEnumConstants.GYYD_REDEMPTION.equals(orderSub)) {
            return OrderTypeEnumConstants.GYYD_CODE;
        } else if (OrderTypeEnumConstants.YHMD.equals(orderSub)) {
            return OrderTypeEnumConstants.YHMD_CODE;
        }
        return OrderTypeEnumConstants.UNKNOW_CODE;
    }
}
